# +~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~ #  
#
#' @title  Create figures and tables in data appendix
#' @author Hauke Licht
#
# +~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~+~ #

# setup ----

library(readr)
library(dplyr)
library(tidyr)
library(purrr)
library(ggplot2)
library(patchwork)

base_path <- file.path(".")
data_path <- file.path(base_path, "data", "output")
helpers_path <- file.path(base_path, "code", "helpers")

source(file.path(helpers_path, "plot_setup.R"))
fig_path <- file.path(base_path, "results", "figures")
dir.create(fig_path, showWarnings = FALSE, recursive = TRUE)

source(file.path(helpers_path, "table_setup.R"))
tables_path <- file.path(base_path, "results", "tables")
dir.create(tables_path, showWarnings = FALSE, recursive = TRUE)

paper_objects <- read_rds(file.path(data_path, "paper_objects.rds"))

# section A ----

## Table S1 ----

paper_objects$tables$parl_configs %>% 
  arrange(country_iso3c) %>% 
  mutate(
    across(matches("_[es]?date"), as.character)
    , across(matches("_[es]?date"), replace_na, replace = "")
  ) %>% 
  quick_kable(
    caption = paste(
      "Parties in parliamentary configurations by country and election."
      , "Part names listed only if (i) the party had at least one seat in parliament \\emph{and} (ii) it was tweeting at least once in the duration of the respective parliamentary configuration."
      , "Party marked bold if it sponsored the prime minister in the given configuration, underlined if it was in government."
      , paste = " "
    )
    , col.names = c("Country", "Election date", "Seats", "$N$", "Names (seats)", "Start", "End",  "$N$", "First", "Last")
    , label = "parl_configs"
    , escape = FALSE
    , longtable = TRUE
  ) %>% 
  add_header_above(
    c(" " = 3, "Recorded parties" = 2, "Parl. configuration" = 2, "Tweets recorded" = 3)
    , bold = TRUE
  ) %>% 
  column_spec(5, width = "4in") %>% 
  collapse_rows(1, latex_hline = "major", valign = "top") %>%
  landscape(margin = "1in") %>%
  write_kable(
    .file.name = "da-tableS01"
    , overwrite = TRUE 
    , dir = tables_path
  )

## Table S2 ----

paper_objects$tables$pre_elec_period_configs %>% 
  quick_kable(
    caption = "Tweet tracking periods for parties entering parliament in an upcoming election."
    , col.names = c("Country", "Upcoming election", "$N$", "Names", "From", "Until",  "$N$", "First", "Last")
    , label = "pre_elec_period_configs"
    , longtable = TRUE
    , escape = FALSE
  ) %>% 
  add_header_above(
    c(" " = 2, "Entering parties" = 2, "Tracked" = 2, "Tweets recorded" = 3)
    , bold = TRUE
  ) %>%
  column_spec(1, bold = TRUE) %>%
  collapse_rows(1:2, latex_hline = "major", valign = "top") %>%
  landscape(margin = "1in") %>% 
  write_kable(
    .file.name = "da-tableS02"
    , overwrite = TRUE
    , dir = tables_path
  )

## Table S3 ----

paper_objects$tables$parl_configs_manually_added %>% 
  select(-election_id, -cabinet_formation) %>% 
  mutate(parl_config_edate = ifelse(is.na(parl_config_edate), "", as.character(parl_config_edate))) %>% 
  quick_kable(
    caption = paste(
      "Parties in manually added parliamentary configurations by country and election."
      , "Party marked bold if it sponsored the prime minister in the given configuration, underlined if it was in government."
      , paste = " "
    )
    , col.names = c("Country", "Election date", "Start", "End", "Seats", "Parties (seats)")
    , label = "parl_configs_manually_added"
    , longtable = TRUE
    , escape = FALSE
  ) %>% 
  add_header_above(
    c(" " = 2, "Parl. configuration" = 2, " " = 2)
    , bold = TRUE
  ) %>%
  column_spec(6, width = "5in") %>%
  collapse_rows(1:2, latex_hline = "full", valign = "top") %>% 
  landscape(margin = "1in") %>% 
  write_kable(
    .file.name = "da-tableS03"
    , overwrite = TRUE
    , dir = tables_path
  )

# Section B ----

## Table S4 ----

paper_objects$tables$elite_criticism_X_political_by_country %>% 
  quick_kable(
    caption = "Numbers and (row) percentages of tweets in outcome classes per country by whether or not their content is likely political."
    , col.names = c(" ", "``Political''", rep(c("$N$", "\\%"), 2))
    , label = "elite_criticism_X_political_by_country"
    , escape = FALSE
    , align = c("r", "c", rep("r", 4))
  ) %>% 
  add_header_above(c(" " = 2, "``Yes''" = 2, "``No''" = 2)) %>% 
  add_header_above(c(" " = 2, "General elite criticism" = 4), bold = TRUE) %>% 
  collapse_rows(1:2, valign = "middle", latex_hline = "none", row_group_label_fonts = list(bold = TRUE)) %>%
  write_kable(.file.name = "da-tableS04", overwrite = TRUE, dir = tables_path)

## Figure S1 ----

cap <- paste(
  "Proportion of party-time units with at least one tweet (left) and distribution of numbers of tweets per time unit on $\\log_{10}$-scale in subset of units with non-zero numbers of tweets (right) by country."
  , "Dark gray shading indicates units with non-zero numbers of tweets."
  , "\\label{fig:n_tweets_distribution_by_country}"
  , collapse = " "
)

save_plot(
  plot = paper_objects$figures$results$n_tweets_distribution_by_country
  , path = fig_path
  , filename = "da-figureS01"
  , devices = "png"
  , width = 5
  , height = 6
)

## Figure S2 ----

cap <- paste(
  "Missingness in party-quarter timeseries."
  , "Shaded areas mark quarters for which parties' tweets have been recorded either because the party was in parliament or it was about to enter parliament in an upcoming election."
  , "Dark shaded areas mark quarters for which no tweets were available and hence party-quarter estimates are missing."
  , "\\label{fig:party_quarter_missingness}"
  , collapse = " "
)

save_plot(
  plot = paper_objects$figures$results$party_quarter_missingness
  , path = fig_path
  , filename = "da-figureS02"
  , devices = "png"
  , width = 5.5
  , height = 8
)

## Figures S3-S8 ----

cap <- paste(
  "Probability-based estimates of parties' anti-elite strategies computed at party-quarters."
  , "One square plotted per party-quarter estimate."
  , "Coloring of squares indicates the estimated salience of anti-elite rhetoric according to the proportion of ``general'' elite criticism instances."
  , "Lighter values correspond to higher salience."
  , "Grey-shaded squares mark party-quarters for which no tweets are available to compute an estimate although the party was included in our dataset in this quarter."
  , "Squares left blank (white) mark periods for which a given party was not included in our dataset in this quarter."
  , "\\label{fig:party_quarters}"
  , collapse = " "
)

n_parties <- map_int(paper_objects$figures$results$party_quarter_plots, "n_parties")

n_parties <- n_parties[names(paper_objects$desc$tweets$countries)]

party_plots <- map(
  split(names(n_parties), cumsum(n_parties) %/% 35)
  , function(ctrs) {
    heights_ <- n_parties[ctrs]
    
    # add one unit for first entry because of legend
    heights_[length(ctrs)] <- heights_[length(ctrs)] + .5
    
    # add legend to first plot
    paper_objects$figures$results$party_quarter_plots[ctrs][[length(ctrs)]]$plot$theme$legend.position <- "bottom"
    
    reduce(
      map(
        paper_objects$figures$results$party_quarter_plots[ctrs]
        , function(obj) {
          p <- obj$plot
          p$data$party_name_short <- gsub("-", "-  ", p$data$party_name_short)
          p
        }
      )
      , `/`
    ) + plot_layout(heights = heights_)
    
  }
)


for (i in 1:length(party_plots)) {
  fn <- sprintf("da-figureS%02d", i+2)
  save_plot(
    plot = party_plots[[i]]
    , path = fig_path
    , filename = fn
    , devices = c("png", "eps")
    , width = 5.5
    , height = 8
  )
}

